package com.xkxx.task.config;

import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.xkxx.task.entity.ScheduleConfigData;
import com.xkxx.task.service.ScheduleConfigDataService;
import com.xkxx.task.task.BatchTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;
import java.util.List;

/**
 * @Author: K-9999
 * @Date: 2022/12/5
 * @Description:
 */
@Configuration
@EnableScheduling
public class ScheduleConfig implements SchedulingConfigurer {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ScheduleConfigDataService scheduleConfigDataService;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        List<ScheduleConfigData> dataList = new LambdaQueryChainWrapper<>(scheduleConfigDataService.getBaseMapper())
                .eq(ScheduleConfigData :: getStatus, "1")
                .list();
        if (dataList.size() > 0) {
            for (ScheduleConfigData date : dataList) {
                taskRegistrar.addTriggerTask(getRunnable(date),
                        triggerContext -> new CronTrigger(date.getCron()).nextExecutionTime(triggerContext));
            }
        }
    }

    private Runnable getRunnable(ScheduleConfigData date){
        return () -> {
            Object task = SpringUtil.getBean(BatchTask.class);
            Method method = ReflectionUtils.findMethod(task.getClass(), date.getMethod());
            ReflectionUtils.invokeMethod(method, task);
        };
    }
}
